package com.nmgydy.util;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;

import com.alibaba.fastjson.JSON;
import com.nmgydy.beans.Message;

public class BeanExceptionResolver extends SimpleMappingExceptionResolver {
	
	@Override
	protected ModelAndView doResolveException(HttpServletRequest request, HttpServletResponse response, Object obj,Exception exception) {
		try {
			String msg = "系统错误";
			exception.printStackTrace();
			boolean isGet = request.getMethod().toLowerCase().equals("get");
			if (isGet) {
				ModelAndView mav=new ModelAndView("error");
				mav.addObject("errorMessage",msg);
				return mav;
			}
			
			response.setStatus(200);
			/*
			if (!Functions.isEmpty(exception.getMessage())) {
				msg = exception.getMessage();
			} else if (exception != null && !Functions.isEmpty(exception.toString())) {
				msg = exception.toString();
				if (msg.length() >= 50) {
					msg = msg.substring(0, 50);
				}
			}
			*/
			Message bean = Message.failure(msg);
			String respMsg = JSON.toJSONString(bean);
			response.setContentType("application/json;charset=utf-8");
			response.setCharacterEncoding("utf-8");
			response.getWriter().print(respMsg);
			response.getWriter().flush();
			response.getWriter().close();
		} catch (Exception e) {
		}
		return null;
	}

}
